package cn.yunwei.module.dingtalk;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author wangbinggui
 */
@Component
public class ModuleCustomRobotGroupMessage {
    private static final Logger log = LoggerFactory.getLogger(ModuleCustomRobotGroupMessage.class);
    public static final String CUSTOM_ROBOT_TOKEN = "120e43e4df1e8aede48141ec4353389c5f6dac8b78abf56b7a59ec0eea03c749";
    //public static final String USER_ID = "186105442529355949";
    //public static final List<String> USER_IDS = Arrays.asList("3025400926674421","186105442529355949"); // 用户 ID 列表
    // 用户手机号列表
    public static final List<String> USER_MOBILES = Arrays.asList("15085164757", "18739632515");
    //public static final String USER_MOBILE = "15085164757";
    public static final String SECRET = "SEC87f3a7cd78a1d88abb32e6535935318abfce0860e1c85ee0b1f79e48a85c9551";


    @XxlJob("sendCustomRobotMessage")
    public void sendCustomRobotMessage() {
        try {
            long timestamp = System.currentTimeMillis();
            String sign = generateSign(SECRET, timestamp);

            log.info("Generated Sign: {}", sign);
            log.info("Timestamp: {}", timestamp);

            sendDingTalkMessage(sign, timestamp);
        } catch (Exception e) {
            log.error("发送自定义机器人消息失败", e);
        }
    }

    private String generateSign(String secret, long timestamp) throws NoSuchAlgorithmException, InvalidKeyException {
        try {
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));

            // 确保 Base64 编码正确，并进行 URL 编码
            return URLEncoder.encode(Base64.encodeBase64String(signData), StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("生成签名失败", e);
        }
    }

    private void sendDingTalkMessage(String sign, long timestamp) {
        try {
            String url = String.format("https://oapi.dingtalk.com/robot/send?access_token=%s&timestamp=%d&sign=%s",
                    CUSTOM_ROBOT_TOKEN, timestamp, sign);
            DingTalkClient client = new DefaultDingTalkClient(url);
            OapiRobotSendRequest req = new OapiRobotSendRequest();

            // 构造消息内容
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent("表检检查通知\n"
                    + "批号:123423455\n"
                    + "订单号: " + timestamp + "\n"+
                    "班组: A班\n" +
                    "点击查料:http://mes.dingshenggroup.com/");
// 构造 At 消息内容

//            // 构造链接消息内容
//            OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();
//            link.setText("这个即将发布的新版本，创始人xx称它为红树林。而在此之前，每当面临重大升级，产品经理们都会取一个应景的代号，这一次，为什么是红树林");
//            link.setTitle("时代的火车向前开");
//            link.setPicUrl(""); // 可选，图片 URL
//            link.setMessageUrl("https://www.dingtalk.com/s?__biz=MzA4NjMwMTA2Ng==&mid=2650316842&idx=1&sn=60da3ea2b29f1dcc43a7c8e4a7c97a16&scene=2&srcid=09189AnRJEdIiWVaKltFzNTw&from=timeline&isappinstalled=0&key=&ascene=2&uin=&devicetype=android-23&version=26031933&nettype=WIFI");

            // 构造 At 消息内容
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            //at.setAtUserIds(Collections.singletonList(USER_ID));
            //at.setAtMobiles(Collections.singletonList(USER_MOBILE));
            //@多个人时用下面的方式
            //at.setAtUserIds(USER_IDS);
            at.setAtMobiles(USER_MOBILES);
            at.setIsAtAll(false);
            // 构造 Markdown 消息内容
//            OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
//            markdown.setTitle("钉钉消息通知");
//            markdown.setText("### 钉钉消息通知\n" +
//                    "#### 消息内容\n" +
//                    "钉钉，让进步发生mes\n" +
//                    "#### 详细信息\n" +
//                    "@15085164757\n" +
//                    "- 时间戳: " + timestamp + "\n" +
//                    "- 签名: " + sign);

            req.setMsgtype("text");
            req.setText(text);
            //req.setMarkdown(markdown);
            req.setAt(at);


            OapiRobotSendResponse rsp = client.execute(req);
            log.info("钉钉机器人消息发送结果: {}", rsp.getBody());
        } catch (ApiException e) {
            log.error("调用钉钉 API 失败", e);
        }
    }
}
